package com.zhengsr.drawbroad.state;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;

import com.zhengsr.drawbroad.DrawBroadApplication;
import com.zhengsr.drawbroad.R;
import com.zhengsr.drawbroad.data.BaseData;
import com.zhengsr.drawbroad.utils.CommandUtils;
import com.zhengsr.drawbroad.utils.ConstractUtils;

/**
 * Created by zhengshaorui on 2018/1/7.
 * csdn: http://blog.csdn.net/u011418943
 */

public class EraserState extends BaseState {
    private static final String TAG = "EraserState";
    private Paint mEraserPaint;
    private Canvas mCanvas;
    private Path mPath;
    private float mLastX,mLastY;
    private Bitmap mEraserBitmap;
    private Rect mSrcRect;
    private final Paint mClearPaint;



    public EraserState() {
        mEraserPaint = new Paint();
        mEraserPaint.setAntiAlias(true);
        mEraserPaint.setFilterBitmap(true);
        mEraserPaint.setStyle(Paint.Style.STROKE);
        mEraserPaint.setAlpha(0);
        mEraserPaint.setColor(Color.TRANSPARENT);
        mEraserPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        int max = ConstractUtils.ERASER_WIDTH*ConstractUtils.ERASER_WIDTH * 2;
        int paintwidth = (int) Math.pow(max,0.5);
        mEraserPaint.setStrokeWidth(paintwidth); //橡皮擦的面积，可以用对角线来给个大概

        BitmapDrawable drawable = (BitmapDrawable) DrawBroadApplication.getContext().getResources().
                getDrawable(R.mipmap.eraser_move);
        mEraserBitmap = drawable.getBitmap();
        mSrcRect = new Rect(0,0,mEraserBitmap.getWidth(),mEraserBitmap.getHeight());

        mClearPaint = new Paint();
        mClearPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
    }

    @Override
    public void onDraw(Canvas canvas) {
        mCanvas = canvas;
    }

    @Override
    public int getMode() {
        return ConstractUtils.ERASER;
    }

    @Override
    public void drawDown(float x, float y) {
        if (mPath == null){
            mPath = new Path();
        }

        mLastX = x;
        mLastY = y;
        mPath.moveTo(x,y);
    }

    @Override
    public void drawMove(float x, float y) {

        //贝塞尔曲线画线
        mPath.quadTo(mLastX,mLastY,(x+mLastX)/2,(y+mLastY)/2);

         mCanvas.drawPath(mPath, mEraserPaint);



        mLastX = x;
        mLastY = y;
    }



    @Override
    public void drawUp() {
        Path cachepath = new Path(mPath);
        BaseData data = new BaseData(cachepath,mEraserPaint);
        CommandUtils.getInstance().add(data);
        mPath.reset();
    }


}
